import React from 'react';
import {connect} from 'dva/index';
import {Button, Col, DatePicker, Form, Input, message, Row, Select, Table} from 'antd';
import Constants from '../../utils/Constants';
import RightConstants from '../../utils/RightConstants';
import RightBox from '../../components/common/rightBox';
import PortSelect from '../../components/common/portSelect';
import QuotationFeeDetail from '../../components/quotation/quotationFee/quotationFeeDetail';
import DeliveryReceiptDetail from '../../components/logisticsOrder/deliveryReceiptDetail';

const R = require('ramda');
const { Option, OptGroup } = Select;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const quotationRecord = Form.create()(class QuotationRecord extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.props.dispatch({ type: 'quotationRecord/getListForPage', payload: { page: Constants.DEFAULT_PAGE } });
        this.props.dispatch({ type: 'quickBooking/getUserQuickBooking', payload: { status: "2" } });
    }

    handleOpen = (id, view, cstEdit, disabled) => {
        this.props.dispatch({
            type: 'currencyRate/getCnyByCurrent',
            payload: {
                currency: "USD"
            }
        });
        this.props.dispatch({
            type: 'quotationFee/getRecordById',
            payload: { id }
        });
        this.quotationFeeDetail.handleOpen( null, null, null, null, view, cstEdit, null, disabled);
    };

    onEdit = (id, freightId, loadingId, destinationId, view, cstEdit, cstInfoDisabled, disabled) => {
        this.props.dispatch({
            type: 'currencyRate/getCnyByCurrent',
            payload: {
                currency: "USD"
            }
        });
        this.props.dispatch({
            type: 'quotationFee/getRecordById',
            payload: { id }
        });
        // this.props.dispatch({
        //     type: 'quotationFee/refreshState',
        //     payload: {
        //         dataSource: {}
        //     }
        // })
        this.quotationFeeDetail.handleOpen(id, freightId, loadingId, destinationId, view, cstEdit, cstInfoDisabled, disabled);
    }

    handleOrder = (id, disabled, cstEdit, quoOrderDisabled, value) => {
        if (!R.isEmpty(this.props.quickBooking.flag)) {
            message.error("您有快速订舱单暂未处理，请优先填写对应交接单！");
            return;
        }

        this.props.dispatch({
            type: 'quotationFee/getRecordById',
            payload: { id }
        });
        
        this.deliveryReceiptDetail.handleOpen(disabled, null, value, cstEdit, null, null, null, false, false, quoOrderDisabled);  
            
    }

    handleDelete = id => {
        this.props.dispatch({
            type: 'quotationRecord/deleteById',
            payload: {
                id,
                onSuccess: this.handleSearch
            }
        })
    };

    handleSearch = flag => {
        let newPage = this.props.quotationRecord.page;
        if (flag) newPage.page = 1;
        this.props.dispatch({
            type: 'quotationRecord/getListForPage',
            payload: {
                ...this.props.form.getFieldsValue(),
                page: newPage
            }
        });
    };

    columns = [
        { title: '客户号', dataIndex: 'customerno', key: 'customerno'},
        { title: '客户名称', dataIndex: 'companyName', key: 'companyName' },
        {
            title: '起运港/目的港', key: 'port',
            render: record => {
                return <span>{record.loadingPortEn}({record.loadingPortName})—>{record.destinationPortEn}({record.destinationPortName})</span>
            }
        },
        { title: '运输类型', render(record) {
            if(record.transportType === '1') {
                return '整柜';
            }else if(record.transportType === '2') {
                return '拼柜';
            }else if(record.transportType === '3'){
                return '拖车';
            }else if(record.transportType === '4'){
                return '空运';
            }else if (record.transportType === '5'){
                return '快递';
            }
        }},
        { title: '状态', key: 'status',
            render: record => {
                if(record.status === '1'){
                    return '草稿';
                }else if(record.status === '2'){
                    return '已确认';
                }
                
            }
        },
        { title: '创建时间', dataIndex: 'createtime', key: 'createtime' },
        { title: '是否有效', dataIndex: 'yx', key: 'yx' },
        {
            title: '操作',
            render: (record) => {
                // let deleteLink = <Popconfirm onConfirm={this.handleDelete.bind(this, record.id)} okText="是" cancelText="否"
                //                              placement="leftTop" title={'数据删除后将不可以恢复，是否继续删除?'}>
                //     <a href="#">删除</a>
                // </Popconfirm>
                // deleteLink = <RightBox resource={RightConstants.QUOTATION.QUOTATION_QUOTATIONRECORD_DELETE} split={true}>{deleteLink}</RightBox>
                let editLink = <RightBox resource={RightConstants.QUOTATION.QUOTATION_QUOTATIONRECORD_EDIT} split={true}>
                <a href="#" onClick={this.onEdit.bind(this, record.id, record.freightId, record.loadingPort, record.destinationPort, true, false, true, false)}>重新编辑</a></RightBox>

                let viewLink = <a href="#" onClick={this.handleOpen.bind(this, record.id, true, true, true)}>详情</a>
                let orderLink = <RightBox resource={RightConstants.QUOTATION.QUOTATION_QUOTATIONRECORD_ORDER} split={true}><a href="#" onClick={this.handleOrder.bind(this, record.id, false, true, true, "1")}>下单</a></RightBox>
                return <span>
                        {record.status === '1' ? editLink : null}{record.status === '2' ? orderLink : null}{viewLink}</span>
            }
        }
    ];

    render() {
        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } };
        const { getFieldDecorator } = this.props.form;
        let pagination = {
            showTotal: total => `共 ${total} 条数据`,
            current: this.props.quotationRecord.page.page,
            pageSize: this.props.quotationRecord.page.size,
            total: this.props.quotationRecord.page.totalRow,
            showSizeChanger: true,
            onShowSizeChange: (current, size) => {
                let newPage = this.props.quotationRecord.page;
                newPage.size = size;
                newPage.page = 1;
                this.props.dispatch({
                    type: 'quotationRecord/getListForPage',
                    payload: {
                        ...this.props.form.getFieldsValue(),
                        page: newPage
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                let newPage = this.props.quotationRecord.page;
                newPage.page = pageNumber;
                this.props.dispatch({
                    type: 'quotationRecord/getListForPage',
                    payload: {
                        ...this.props.form.getFieldsValue(),
                        page: newPage
                    }
                });
            }
        }

        return (
            <div>
                <Row>
                    <Col span={8}><FormItem {...formItemLayout} label={'客户号'}>{getFieldDecorator('cstNo')(<Input maxLength="20" placeholder="可根据客户号搜索" />)}</FormItem></Col>
                    <Col span={8}><FormItem {...formItemLayout} label={'客户名称'}>{getFieldDecorator('cstName')(<Input maxLength="20" placeholder="可根据公司名称搜索" />)}</FormItem></Col>
                </Row>
                <Row>
                    <Col span={8}><FormItem {...formItemLayout} label={'起运港'}>{getFieldDecorator('loadingPort')(<PortSelect style={{ width: '100%' }} allowClear />)}</FormItem></Col>
                    <Col span={8}><FormItem {...formItemLayout} label={'目的港'}>{getFieldDecorator('destinationPort')(<PortSelect style={{ width: '100%' }} allowClear />)}</FormItem></Col>
                </Row>
                <Row>
                    <Col span={8}>
                    <FormItem {...formItemLayout} label="物流运输类型">
                        {getFieldDecorator('type',{
                            initialValue: "1"
                        })
                        (
                            <Select style={{ width: '100%' }} allowClear>
                                <Select.Option value="1">整柜</Select.Option>
                                <Select.Option value="2">拼柜</Select.Option>
                                <Select.Option value="3">拖车</Select.Option>
                                <Select.Option value="4">空运</Select.Option>
                                <Select.Option value="5">快递</Select.Option>
                            </Select>
                        )}
                    </FormItem>
                </Col>
                    <Col span={8}>
                        <FormItem  {...formItemLayout} label={'创建时间'}>
                            {getFieldDecorator('createtime', {})(
                                <RangePicker
                                    beginTime={{ format: 'YYYY-MM-DD' }}
                                    endTime="YYYY-MM-DD"
                                    placeholder={['开始时间', '结束时间']}
                                />
                            )}
                        </FormItem>
                    </Col>
                    <Col span={7} style={{ marginLeft: 24 }}>
                        <Button type="primary" icon="search" style={{ marginRight: 5 }} onClick={this.handleSearch.bind(this, true)}>查询</Button>
                    </Col>
                </Row>

                <Table loading={this.props.loading} rowKey='id' dataSource={this.props.quotationRecord.list} columns={this.columns} bordered={true} size={'middle'} pagination={pagination} />
                <QuotationFeeDetail wrappedComponentRef={(inst) => this.quotationFeeDetail = inst} refreshList={this.handleSearch} view={true}/>
                <DeliveryReceiptDetail wrappedComponentRef={(inst) => this.deliveryReceiptDetail = inst} refreshList={this.handleSearch} />
            </div>
        )
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.quotationRecord, quotationRecord: state.quotationRecord, quotationFee: state.quotationFee, quickBooking: state.quickBooking,
                deliveryReceipt: state.deliveryReceipt
    };
}

export default connect(mapStateToProps)(quotationRecord);